import React, { useEffect, useState } from 'react';
import {
  collection,
  query,
  orderBy,
  limit,
  getDocs,
  where,
  startAfter,
  QueryDocumentSnapshot,
  DocumentData,
} from 'firebase/firestore';
import { db } from '../services/firebase';
import CopywritingCard from '../components/features/CopywritingCard';
import SearchBar from '../components/features/SearchBar';
import { Copywriting } from '../types';

const ITEMS_PER_PAGE = 9;

const categories = [
  { id: 'all', name: '全部' },
  { id: 'marketing', name: '营销文案' },
  { id: 'social', name: '社交媒体' },
  { id: 'slogan', name: '广告语' },
  { id: 'content', name: '内容创作' },
  { id: 'other', name: '其他' },
];

const Home = () => {
  const [copywritings, setCopywritings] = useState<Copywriting[]>([]);
  const [loading, setLoading] = useState(true);
  const [loadingMore, setLoadingMore] = useState(false);
  const [hasMore, setHasMore] = useState(true);
  const [selectedCategory, setSelectedCategory] = useState('all');
  const [lastDoc, setLastDoc] = useState<QueryDocumentSnapshot<DocumentData> | null>(null);

  const fetchCopywritings = async (isLoadMore = false) => {
    try {
      setLoading(!isLoadMore);
      setLoadingMore(isLoadMore);

      let q = query(
        collection(db, 'copywriting'),
        where('status', '==', 'published'),
        orderBy('createdAt', 'desc'),
        limit(ITEMS_PER_PAGE)
      );

      if (selectedCategory !== 'all') {
        q = query(
          collection(db, 'copywriting'),
          where('status', '==', 'published'),
          where('category', '==', selectedCategory),
          orderBy('createdAt', 'desc'),
          limit(ITEMS_PER_PAGE)
        );
      }

      if (isLoadMore && lastDoc) {
        q = query(
          collection(db, 'copywriting'),
          where('status', '==', 'published'),
          ...(selectedCategory !== 'all' ? [where('category', '==', selectedCategory)] : []),
          orderBy('createdAt', 'desc'),
          startAfter(lastDoc),
          limit(ITEMS_PER_PAGE)
        );
      }

      const querySnapshot = await getDocs(q);
      const copywritingList = querySnapshot.docs.map(
        (doc) => ({ id: doc.id, ...doc.data() } as Copywriting)
      );

      if (isLoadMore) {
        setCopywritings((prev) => [...prev, ...copywritingList]);
      } else {
        setCopywritings(copywritingList);
      }

      setLastDoc(querySnapshot.docs[querySnapshot.docs.length - 1] || null);
      setHasMore(querySnapshot.docs.length === ITEMS_PER_PAGE);
    } catch (error) {
      console.error('Error fetching copywritings:', error);
    } finally {
      setLoading(false);
      setLoadingMore(false);
    }
  };

  useEffect(() => {
    fetchCopywritings();
  }, [selectedCategory]);

  const handleLoadMore = () => {
    if (!loadingMore && hasMore) {
      fetchCopywritings(true);
    }
  };

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <div className="text-center mb-12">
        <h1 className="text-4xl font-bold text-gray-900 mb-4">
          妙笔 - 优质文案分享平台
        </h1>
        <p className="text-gray-600 mb-8">发现、创作和分享优质文案</p>
        <div className="flex justify-center">
          <SearchBar />
        </div>
      </div>

      {/* 分类筛选 */}
      <div className="flex justify-center mb-8">
        <div className="inline-flex rounded-md shadow-sm">
          {categories.map((category) => (
            <button
              key={category.id}
              onClick={() => setSelectedCategory(category.id)}
              className={`px-4 py-2 text-sm font-medium ${
                selectedCategory === category.id
                  ? 'bg-blue-600 text-white'
                  : 'bg-white text-gray-700 hover:bg-gray-50'
              } ${
                category.id === categories[0].id
                  ? 'rounded-l-md'
                  : category.id === categories[categories.length - 1].id
                  ? 'rounded-r-md'
                  : ''
              } border border-gray-300 focus:z-10 focus:outline-none focus:ring-1 focus:ring-blue-500`}
            >
              {category.name}
            </button>
          ))}
        </div>
      </div>

      {loading ? (
        <div className="flex justify-center items-center min-h-[400px]">
          <div className="text-lg">加载中...</div>
        </div>
      ) : copywritings.length === 0 ? (
        <div className="text-center py-12">
          <p className="text-gray-500 text-lg">
            {selectedCategory === 'all'
              ? '暂无文案，快来创建第一篇吧！'
              : '该分类下暂无文案'}
          </p>
        </div>
      ) : (
        <>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {copywritings.map((copywriting) => (
              <CopywritingCard key={copywriting.id} copywriting={copywriting} />
            ))}
          </div>

          {hasMore && (
            <div className="flex justify-center mt-8">
              <button
                onClick={handleLoadMore}
                disabled={loadingMore}
                className="px-6 py-3 text-sm font-medium text-blue-600 bg-white border border-blue-600 rounded-md hover:bg-blue-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50"
              >
                {loadingMore ? '加载中...' : '加载更多'}
              </button>
            </div>
          )}
        </>
      )}
    </div>
  );
};

export default Home;
